<template>
  <div>
    <Navbar appTitle="新建保养" />
    <div
      class="search-content wrap-apply"
      :style="{
        top: GLOBAL.currentEnvironment ? '0' : '',
        height: GLOBAL.currentEnvironment ? '100vh' : 'calc(100vh - 1.12rem)',
        paddingBottom: GLOBAL.currentEnvironment ? '0.66rem' : '',
      }"
    >
      <van-cell-group style="margin-top: 0.1rem">
        <p class="label required FormTit"><span></span>扫码设备</p>
        <scanInput
          ref="scanInput"
          :columns="columns"
          @changeScan="changeScan"
        />
        <div class="bottomLine"></div>
      </van-cell-group>
      <van-cell-group>
        <p class="label FormTit"><span></span>设备类别</p>
        <van-field
          readonly
          v-model="buildForm.deviceCategoryText"
          placeholder="请先选择故障设备"
        />
        <div class="bottomLine"></div>
      </van-cell-group>

      <van-cell-group
        style="margin-top: 0.1rem"
        v-for="(p, i) in messDeviceMaintainTaskItem"
        :key="i"
      >
        <p
          class="label otherText"
          style="display: flex; justify-content: space-between"
        >
          保养项目（{{ i + 1 }}）<span
            style="font-weight: 400; color: #ff4d4f"
            @click="messDeviceMaintainTaskItem.splice(i, 1)"
            v-if="messDeviceMaintainTaskItem.length > 1"
            >删除</span
          >
        </p>
        <div class="bottomLine"></div>
        <p class="label required FormTit"><span></span>保养项</p>
        <van-field
          readonly
          :is-link="!p.projectText"
          placeholder="请选择"
          v-model="p.projectText"
          @click="projectVisible(i)"
        >
          <div
            slot="right-icon"
            v-show="!!p.projectText"
            @click.stop="handleConfirm('',i)"
          >
            <img
              src="~@/assets/img/filedClear.png"
              alt=""
              style="width: 0.16rem"
            />
          </div>
        </van-field>
        <div class="bottomLine"></div>
        <p class="label FormTit"><span></span>保养标准</p>
        <van-field
          readonly
          placeholder="请选择保养项"
          v-model="p.maintainStandard"
        />
        <div class="bottomLine"></div>
        <p class="label required FormTit"><span></span>保养描述</p>
        <van-field placeholder="请输入" v-model="p.maintainDescribe" maxlength="500"/>
      </van-cell-group>
      <div class="addgoods" @click="messDeviceMaintainTaskItem.push({})">
        <a>+添加</a>
      </div>

      <van-cell-group style="margin-top: 0.1rem">
        <p class="label otherText">其他</p>
        <div class="bottomLine"></div>
        <p class="label">备注</p>
        <van-field
          v-model="buildForm.remark"
          rows="2"
          autosize
          label=""
          type="textarea"
          maxlength="500"
          placeholder="请输入备注"
          show-word-limit
        />
        <div class="bottomLine"></div>
      </van-cell-group>
      <van-cell-group>
        <!-- <upload iconType="fj" @fileChange="fileChange" :fileIds="attachment" /> -->
        <fileSelector
          iconType="fj"
          :title="'附件'"
          @fileChange="fileChange"
          :fileIds="attachment"
        ></fileSelector>
      </van-cell-group>
      <div class="search-bottoms">
        <van-button
          :loading="loadingSub"
          type="info"
          loading-text="提交中..."
          class="btnconfirm"
          @click="btnConfirm('finish')"
          >提交</van-button
        >
      </div>
    </div>
    <van-popup v-model="visibles" position="bottom">
      <van-picker
        :columns="options"
        @confirm="handleConfirm"
        @cancel="visibles = false"
        show-toolbar
      />
    </van-popup>
  </div>
</template>
<script>
import {
  pageQueryDeviceEntity,
  messDeviceMaintainItemList,
  messDeviceMaintainTaskAdd,
  messDeviceQueryById,
} from "@/api/system";
import Navbar from "@/components/navBar/navBar_right";
import scanInput from "@/components/scanCode/scanInput";
import ContactPickers from "@/components/choiceuse/ContactPickers";
import upload from "@/components/upload/upload";
import VanFieldSelectPicker from "@/components/ActionSheet/VanFieldSelectPicker";
import VanFieldCheckbox from "@/components/ActionSheet/VanFieldCheckbox";
// import {} from "@/utils/util";
import Examine from "@/components/examine";
import fileSelector from "@/components/fileSelector.vue";
export default {
  name: "search",
  components: {
    ContactPickers,
    upload,
    VanFieldSelectPicker,
    VanFieldCheckbox,
    Navbar,
    scanInput,
    Examine,
    fileSelector
  },
  data() {
    return {
      deviceId: "",
      visibles: false,
      buildForm: {
        deviceId: undefined,
        deviceCategoryText: "",
        remark: "",
      },
      columns: [],
      deviceList: [], //完整的工单编号列表
      attachment: "", //附件
      formPage: "",
      currentLoginUser: {},
      messDeviceMaintainTaskItem: [{}],
      options: [],
      listIndex: null,
      loadingSub: false,
    };
  },
  computed: {},
  created() {
    this.currentLoginUser = JSON.parse(
      localStorage.getItem("pro__Login_Userinfo")
    ).value;
    this.deviceId = this.$route.query.deviceId;
    this.formPage = this.$route.query.formPage;
    if (this.formPage == "scanCode" && this.$route.query.code) {
      this.changeScan({ code: this.$route.query.code }, "scan");
    }
    this.getInitData();
  },
  methods: {
    // 选择保养项
    handleConfirm(v,i) {
      console.log(v, this.listIndex);
      if (!v) {
        this.$nextTick(() => {
          this.messDeviceMaintainTaskItem[i].itemId = "";
          this.messDeviceMaintainTaskItem[i].maintainStandard = "";
          this.messDeviceMaintainTaskItem[i].projectText = "";
          this.messDeviceMaintainTaskItem[i].projectCode = "";
          this.messDeviceMaintainTaskItem[i].projectName = "";
          this.visibles = false;
        });
        this.$forceUpdate();

        return;
      }
      if (this.messDeviceMaintainTaskItem[this.listIndex].itemId == v.id) {
        this.visibles = false;
        return;
      }
      let items = this.messDeviceMaintainTaskItem.find(
        (item) => item.itemId == v.id
      );
      if (items) {
        this.$toast("该保养项已存在，请直接修改数据");
        this.visibles = false;
        return;
      }
      this.messDeviceMaintainTaskItem[this.listIndex].itemId = v.id;
      this.messDeviceMaintainTaskItem[this.listIndex].maintainStandard =
        v.maintainStandard;
      this.messDeviceMaintainTaskItem[this.listIndex].projectText = v.text;
      this.messDeviceMaintainTaskItem[this.listIndex].projectCode =
        v.projectCode;
      this.messDeviceMaintainTaskItem[this.listIndex].projectName =
        v.projectName;
      this.visibles = false;
    },
    projectVisible(i) {
      this.visibles = true;
      this.listIndex = i;
    },
    //页面加载请求数据
    getInitData() {
      pageQueryDeviceEntity({ pageSize: 999, pageNo: 1 }).then((res) => {
        if (res.success) {
          this.deviceList = res.result.records;
          this.columns = [];
          for (let item of res.result.records) {
            let obj = {
              key: `${item.deviceCode}-${item.deviceName}`,
              value: item.id,
              deviceCategoryText: item.deviceCategoryText,
            };
            this.columns.push(obj);
          }
        } else {
          this.$toast(res.message);
        }
      });
      messDeviceMaintainItemList({ pageSize: 999, pageNo: 1 }).then((res) => {
        if (res.result.records) {
          for (let i = 0; i < res.result.records.length; i++) {
            let t = res.result.records[i];
            t.text = `${t.projectCode}-${t.projectName}`;
            t.value = t.id;
            this.options.push(t);
          }
        }
      });
    },
    changeScan(v, opratorType) {
      console.log(v, "获取扫码组件数据");
      //value是下拉选择后值,code是扫码获得的值，根据qrcode判断是否隐藏当前页面只显示相机页
      if (opratorType == "select" && this.buildForm.deviceId != v.value) {
        this.buildForm.deviceId = v.value;
        this.buildForm.deviceCategoryText = v.deviceCategoryText || "--";
        console.log(this.buildForm);
      }
      if (opratorType == "scan") {
        if (v.code.EntityType != "device") {
          this.$toast("请扫正确二维码");
          return;
        }
        this.buildForm.deviceId = v.code.id;
        let obj = {
          id: v.code.id, // 设备id,用id查设备详情做回显
        };
        messDeviceQueryById(obj).then((res) => {
          if (res.code == 200) {
            this.buildForm.deviceCategoryText =
              res.result.deviceCategoryText || "--";
            let scanObj = {
              id: this.buildForm.deviceId,
              orderCode: `${res.result.deviceCode}-${res.result.deviceName}`,
            };
            this.$refs.scanInput.propValue(scanObj);
          }
        });
      }
    },
    fileChange(ids) {
      this.attachment = ids;
    },
    // 提交
    btnConfirm() {
      if (!this.buildForm.deviceId) {
        this.$toast("请选择设备");
        return;
      }
      for (let i = 0; i < this.messDeviceMaintainTaskItem.length; i++) {
        const item = this.messDeviceMaintainTaskItem[i];
        if (!item.itemId) {
          this.$toast(`保养项目（${i + 1}）保养项必填`);
          return;
        }
        if (!item.maintainDescribe) {
          this.$toast(`保养项目（${i + 1}）保养描述必填`);
          return;
        }
      }
      this.handleSubmit();
    },
    handleSubmit() {
      let params = {
        ...this.buildForm,
        attachment: this.attachment,
        messDeviceMaintainTaskItem: this.messDeviceMaintainTaskItem,
      };
      console.log("检查一下参数：", params);
      this.loadingSub = true;
      messDeviceMaintainTaskAdd(params).then((res) => {
        this.loadingSub = false;
        if (res.code == 200) {
          this.$toast("新建成功");
          this.$router.go(-1);
        } else {
          this.$toast(res.message);
        }
      });
    },
  },
};
</script>
<style lang="scss" scoped>
@import "@/assets/theme.scss";
.search-content {
  //  padding-bottom: 0.5rem;
  position: fixed;
  top: 0.42rem;
  width: 100%;
  height: calc(100vh - 1.12rem);
  background: #f5f5f5;
  overflow: scroll;
  z-index: 99;
  .formgroup {
    background: #ffffff;
    // padding: 0 0.16rem;
    margin-top: 0.1rem;
    margin-bottom: 0.2rem;
    padding-top: 0.1rem;

    .title {
      width: 0.58rem;
      height: 0.14rem;
      font-size: 0.15rem;
      font-family: PingFang SC;
      font-weight: 400;
      color: #191f25;
      line-height: 0.05rem;
      margin-left: 0.16rem;
    }
  }
}
.bottomLine {
  height: 0.01rem;
  background-color: #f0f0f0;
  margin: 0 0.16rem;
}
.otherText {
  padding-bottom: 0.16rem;
  font-size: 0.16rem;
  font-weight: bold;
  color: #191f25;
}
.haveUnitBox {
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-sizing: border-box;
  padding-right: 0.16rem;
  /deep/ .van-cell {
    padding-right: 0;
    width: 2.6rem;
  }
  /deep/ .van-field__control {
    max-width: 3rem;
  }
}
/deep/ .van-nav-bar {
  z-index: 99;
}
.search-bottoms {
  width: 100%;
  height: 0.5rem;
  background: #ffffff;
  display: flex;
  justify-content: space-between;
  align-items: center;
  position: fixed;
  bottom: 0px;
  padding: 0rem 0.11rem;
  box-sizing: border-box;
  font-size: 0.16rem;
  font-weight: 500;
  z-index: 9;
  .btncancel {
    flex: 1;
    background: #f6f6f6;
    border: 0.01rem solid rgba(25, 31, 37, 0.12);
    box-sizing: border-box;
    height: 0.39rem;
    display: flex;
    justify-content: center;
    align-items: center;
    border-radius: 0.03rem;
    margin-right: 0.11rem;
    color: #191f25;
  }
  .btnconfirm {
    flex: 1;
    background: #1890ff;
    box-sizing: border-box;
    height: 0.39rem;
    display: flex;
    justify-content: center;
    align-items: center;
    border-radius: 0.03rem;
    color: #ffffff;
  }
}
.addgoods {
  background: #fff;
  font-size: 0.16rem;
  text-align: center;
  height: 0.5rem;
  line-height: 0.5rem;
}
</style>
